//
//  ViewController.swift
//  windeclear
//
//  Created by 黄龙 on 2022/9/16.
//

import UIKit
//import SwiftyJSON
//import Realm
//import RealmSwift //11.0以上系统才能使用



class ViewController: UIViewController {
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.backgroundColor = .systemYellow;
        
        let label_1 = UILabel(frame: CGRect(x: 30, y: 100, width: 300, height: 60));
        label_1.text = "哈哈，我的swift";
        label_1.textAlignment = .center;
        label_1.backgroundColor = .cyan;//.clear;
        label_1.textColor = .red;
        label_1.font = .systemFont(ofSize: 20, weight: UIFont.Weight.black); //UIFont.Weight.black黑色粗体
        self.view.addSubview(label_1);
        
        var i_py=100+60+30;
        let btn_1: UIButton = UIButton(type: UIButton.ButtonType.custom)
        btn_1.setTitle("alert_1", for: UIControl.State())
        btn_1.backgroundColor = .cyan
//        btn_1.titleLabel?.textColor = .systemBlue //设置无效
        btn_1.setTitleColor(UIColor.systemBlue, for: UIControl.State.normal)
        btn_1.titleLabel?.font = .systemFont(ofSize: 14, weight: UIFont.Weight.black)
        btn_1.isUserInteractionEnabled = true
        btn_1.tag = 0
        btn_1.frame = CGRect(x: 30, y: i_py, width: 140, height: 40)
        btn_1.addTarget(self, action: #selector(pressedBtn(_:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btn_1)
        
        i_py+=60;
        let btn_2: UIButton = UIButton(type: UIButton.ButtonType.custom)
        btn_2.setTitle("alert_2", for: UIControl.State())
        btn_2.backgroundColor = .cyan
        btn_2.setTitleColor(UIColor.systemBlue, for: UIControl.State.normal)
        btn_2.titleLabel?.font = .systemFont(ofSize: 14, weight: UIFont.Weight.black)
        btn_2.isUserInteractionEnabled = true
        btn_2.tag = 1
        btn_2.frame = CGRect(x: 30, y: i_py, width: 140, height: 40)
        btn_2.addTarget(self, action: #selector(pressedBtn(_:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btn_2)
        
        i_py+=60;
        let btn_3: UIButton = UIButton(type: UIButton.ButtonType.custom)
        btn_3.setTitle("alert_3", for: UIControl.State())
        btn_3.backgroundColor = .cyan
        btn_3.setTitleColor(UIColor.systemBlue, for: UIControl.State.normal)
        btn_3.titleLabel?.font = .systemFont(ofSize: 14, weight: UIFont.Weight.black)
        btn_3.isUserInteractionEnabled = true
        btn_3.tag = 2
        btn_3.frame = CGRect(x: 30, y: i_py, width: 140, height: 40)
        btn_3.addTarget(self, action: #selector(pressedBtn(_:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btn_3)
        
        i_py+=60;
        let btn_4: UIButton = UIButton(type: UIButton.ButtonType.custom)
        btn_4.setTitle("alert_4", for: UIControl.State())
        btn_4.backgroundColor = .cyan
        btn_4.setTitleColor(UIColor.systemBlue, for: UIControl.State.normal)
        btn_4.titleLabel?.font = .systemFont(ofSize: 14, weight: UIFont.Weight.black)
        btn_4.isUserInteractionEnabled = true
        btn_4.tag = 3
        btn_4.frame = CGRect(x: 30, y: i_py, width: 140, height: 40)
        btn_4.addTarget(self, action: #selector(pressedBtn(_:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btn_4)
        
        i_py+=60;
        let btn_5: UIButton = UIButton(type: UIButton.ButtonType.custom)
        btn_5.setTitle("alert_5", for: UIControl.State())
        btn_5.backgroundColor = .cyan
        btn_5.setTitleColor(UIColor.systemBlue, for: UIControl.State.normal)
        btn_5.titleLabel?.font = .systemFont(ofSize: 14, weight: UIFont.Weight.black)
        btn_5.isUserInteractionEnabled = true
        btn_5.tag = 4
        btn_5.frame = CGRect(x: 30, y: i_py, width: 140, height: 40)
        btn_5.addTarget(self, action: #selector(pressedBtn(_:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btn_5)
        
        i_py+=60;
        let btn_6: UIButton = UIButton(type: UIButton.ButtonType.custom)
        btn_6.setTitle("alert_6", for: UIControl.State())
        btn_6.backgroundColor = .cyan
        btn_6.setTitleColor(UIColor.systemBlue, for: UIControl.State.normal)
        btn_6.titleLabel?.font = .systemFont(ofSize: 14, weight: UIFont.Weight.black)
        btn_6.isUserInteractionEnabled = true
        btn_6.tag = 5
        btn_6.frame = CGRect(x: 30, y: i_py, width: 140, height: 40)
        btn_6.addTarget(self, action: #selector(pressedBtn(_:)), for: UIControl.Event.touchUpInside)
        self.view.addSubview(btn_6)
        
//        ------------swiftyJSON库的使用
        var json: JSON = JSON.null
        if let file = Bundle.main.path(forResource: "SwiftyJSONTests", ofType: "json") {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: file))
                json = try JSON(data: data)
                let slog = "SwiftyJSON:(\(json.type))[\(json.count)]"
                label_1.text = slog
                HL_Log(slog)
                if let firstDict = json[0].dictionary {
                    HL_Log(message: "SwiftyJSON:id_str = \(String(describing: firstDict["id_str"]?.string)) + created_at:\(String(describing: firstDict["created_at"]?.string))")
                    
                    if let source = firstDict["source"]?.string {
                        HL_Log("SwiftyJSON:source:\(source)")
                    }
                }
            } catch {
                json = JSON.null
            }
        }
        
//swiftyJSON与URLSession结合
        let url = URL(string:"https://httpbin.org/get") //http://www.hangge.com/getJsonData.php
        let request = URLRequest(url: url!)

        let dataTask = URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
            if error != nil {
                HL_Log("GetUrlFail:\(String(describing: error))")
            }else{
                let urljson = try? JSON(data: data!)
                if let uAgent = urljson?["headers"]["User-Agent"].string {
                        HL_Log(message:"User-Agent：\(uAgent)")
                }
            }
        }) as URLSessionTask
        dataTask.resume()

//swiftyJSON与Alamofire结合
        struct HTTPBinResponse: Decodable { let url: String }
        AF.request("https://httpbin.org/get").responseDecodable(of: HTTPBinResponse.self) { response in
            HL_Log("Response: \(response)")
            if let data = response.data{
                let urljson = JSON(data)
                if let uAgent = urljson["headers"]["User-Agent"].string {
                        HL_Log(message:"User-Agent：\(uAgent)")
                }
            }else{
                HL_Log(message:"response.data.is.nil")
            }
            
        }

        
        
        AF.request(url!).validate().responseJSON { response in
            switch response.result.isSuccess{
                case true:
                    if let jsonValue = response.data {
                        let urljson = JSON(jsonValue)
                        if let uAgent = urljson["headers"]["User-Agent"].string {
                                HL_Log(message:"User-Agent：\(uAgent)")
                        }
                    }
                break;

                case false:
                    HL_Log("error")
                break;
            }
        }
        
        var iCount = 0
        Async.background {
            HL_Log("A: This is run on the \(qos_class_self().description) (expected \(QOS_CLASS_BACKGROUND.description))")
//QoS（quality of service）意指服务质量，它影响线程优先级（priority), 可以用 qos_class_self() 接口获得当前线程 / 队列的 QoS
            for i in 1...100000 {
                iCount += i
               HL_Log(message: "Async.backgroud:\(iCount)")
            }
        }.main {
            HL_Log("B: This is run on the \(qos_class_self().description) (expected \(qos_class_main().description)), after the previous block")
            label_1.text = "Game Over \(iCount)"
        }
        
        
        
    }
    
    @objc func pressedBtn(_ sender: UIButton!) {
//        self.closeAlert(sender.tag)
        HL_LogLine("press:btn[\(sender.tag)]")
        switch sender.tag {
        case 0:
            _ = SweetAlert().showAlert("Here's a message!")
        case 1:
            _ = SweetAlert().showAlert("Here's a message!", subTitle: "It's pretty, isn't it?", style: AlertStyle.none)
        case 2:
            _ = SweetAlert().showAlert("Good job!", subTitle: "You clicked the button!", style: AlertStyle.success)
        case 3:
            _ = SweetAlert().showAlert("Are you sure?", subTitle: "You file will permanently delete!", style: AlertStyle.warning, buttonTitle:"Cancel", buttonColor:UIColor.colorFromRGB(0xD0D0D0) , otherButtonTitle:  "Yes, delete it!", otherButtonColor: UIColor.colorFromRGB(0xDD6B55)) { (isOtherButton) -> Void in
                if isOtherButton == true {
                
                    print("Cancel Button  Pressed", terminator: "")
                }
                else {
                    _ = SweetAlert().showAlert("Deleted!", subTitle: "Your imaginary file has been deleted!", style: AlertStyle.success)
                }
            }
        case 4:
            _ = SweetAlert().showAlert("Are you sure?", subTitle: "You file will permanently delete!", style: AlertStyle.warning, buttonTitle:"No, cancel plx!", buttonColor:UIColor.colorFromRGB(0xD0D0D0) , otherButtonTitle:  "Yes, delete it!", otherButtonColor: UIColor.colorFromRGB(0xDD6B55)) { (isOtherButton) -> Void in
                if isOtherButton == true {
                    
                    _ = SweetAlert().showAlert("Cancelled!", subTitle: "Your imaginary file is safe", style: AlertStyle.error)
                }
                else {
                    _ = SweetAlert().showAlert("Deleted!", subTitle: "Your imaginary file has been deleted!", style: AlertStyle.success)
                }
            }
        default:
            _ = SweetAlert().showAlert("Sweet!", subTitle: "Here's a custom image.", style: AlertStyle.customImage(imageFile: "thumb.jpg"))
        }
    }



}

